<template>
    <div>
        <!-- 租客入住 -->
        <Modal
            v-model="isModalVisible"
            :closable="false"
            :mask-closable="false"
            :loading="true"
            title="租客续住"
            width="640">
            <Form ref="checkInForm" :label-width="120"
            style="height: 100%;">
                <Row class="renter-list-info margin-bot-16">
                    <Col span="4" class="info-title">租客姓名：</Col>
                    <Col span="9">{{renter.name || '-' }}</Col>
                </Row>
                <Row class="renter-list-info margin-bot-16">
                    <Col span="4" class="info-title">手机号码：</Col>
                    <Col span="7">{{renter.phone || '-'}}</Col>
                </Row>

                <Row class="renter-list-info margin-bot-5" type="flex" align="middle">
                    <Col span="4" class="info-title">房间地址：</Col>
                    <Col span="9">{{lease.home_address}}</Col>
                </Row>
                <Row class="renter-list-info margin-bot-5" type="flex" align="middle">
                    <Col span="4" class="info-title">房间名称：</Col>
                    <Col span="7">{{lease.room_name}}</Col>
                </Row>

                <div class="split-line" v-if="lease.co_tenants.length"></div>
                <Row class="renter-list-cells margin-bot-5" v-for="(item,index) in lease.co_tenants" :key="index">
                    <Col span="4" style="text-align:right">同租人：</Col>
                    <Col span="3">{{item.name }}</Col>
                    <Col span="3" style="text-align:right">电话：</Col>
                    <Col span="3">{{item.phone}}</Col>
                    <Col span="4" style="text-align:right">关系：</Col>
                    <Col span="7">{{item.co_tenant_lease && item.co_tenant_lease.relationship}}</Col>
                </Row>

                <div class="split-line"></div>

                <Alert type="warning">因安全考虑，续约后请对需要延期的密码单独延期</Alert>
                <FormItem label="续租有效期：" class="margin-bot-5">
                    <span>{{new Date(lease.lease_range[0]).Format('yyyy-MM-dd HH:mm:ss')}} - </span>
                    <DatePicker
                    type="datetime"
                    placement="bottom"
                    placeholder="选择续租有效期"
                    :options="options3"
                    v-model="checkInDate"
                    style="width: 280px"></DatePicker>
                </FormItem>

                <div class="split-line"></div>

                <!-- <passwordsTable v-if="showPasswordsTable" :roomId="roomInfo.id" :passwords="passwords"> </passwordsTable>
                <br> -->

                <FormItem label="开门有效期：" v-if="!hasLock">
                    <div>暂无门锁</div>
                </FormItem>

                <!-- <FormItem label="开门有效期：" v-else>
                    <span>{{new Date(lease.lease_range[0]).Format('yyyy-MM-dd HH:mm:ss')}} - </span>
                    <DatePicker
                    type="datetime"
                    placement="top"
                    placeholder="可选，默认为租约有效期"
                    :options="options3"
                    v-model="passwordDate"
                    style="width: 280px"></DatePicker>
                </FormItem> -->

                <div class="split-line"></div>

                <FormItem v-if="!hasElemeter" label="当前电表读数：" class="margin-bot-5">
                    暂无电表
                </FormItem>

                <FormItem v-if="overdraft && hasElemeter" label="当前电表读数：" class="margin-bot-5">
                    {{roomInfo.electric_read || 0}} KWH （更新于 {{new Date(roomInfo.updated_at || Date.now()).Format('yyyy/MM/dd HH:mm')}}）
                </FormItem>
                <FormItem v-if="!overdraft && hasElemeter" label="当前剩余电量：" class="margin-bot-5">
                    {{ leftElectric }} KWH （更新于 {{new Date(roomInfo.updated_at || Date.now()).Format('yyyy/MM/dd HH:mm')}}）
                </FormItem>

            </Form>

            <div slot="footer">
                <Button type="ghost" size="large" @click="cancelContinue('checkInForm')">取消</Button>
                <Button :loading="!renter.id || isLoading" type="primary" size="large" @click="checkIn('checkInForm')">续租</Button>
            </div>
        </Modal>
        <operateResultModal v-if="isResultModalVisible" @confirm="closeContinueModal" :operateResult="operateResult" :operateResultMulti="operateResultMulti"></operateResultModal>

    </div>


</template>

<script>
// import validate from '@/libs/validate';
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'
import passwordsTable from './passwordsTable'
import operateResultModal from './operateResultModal'

export default {
  props: {
    renterId: {
      // 租客Id,必须
      required: true
    },
    lease: {
      // 租赁房间信息
      type: Object,
      required: true
    },
    hasFaceDeviceAndPermission: {
      type: Boolean,
      default: false
    }
  },
  components: {
    passwordsTable,
    operateResultModal
  },
  data () {
    return {
      operateResult: [],
      isResultModalVisible: false,
      isModalVisible: true,
      passwords: {},
      renter: {},
      checkInDate: '', // 租约有效期
      roomInfo: {}, // 具体房间信息
      parentRoomInfo: {},
      passwordType: 0, // 是否授权密码
      passwordDate: '',
      operateResultMulti: null, // 一个接口返回多个状态的情况
      passwordTypes: [
        {
          value: 1,
          label: '授权普通密码'
        },
        {
          value: 0,
          label: '不授权'
        }
      ],
      options3: {
        disabledDate: date => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      isLoading: false,
      showPasswordsTable: false
    }
  },
  watch: {
    checkInDate (n, o) {
      this.passwordDate = n
    }
  },
  created () {
    this.getRoomInfo(this.lease.room_id)

    this.checkInDate = new Date(this.lease.lease_range[1])
    this.passwordDate = new Date(this.lease.lease_range[1])

    http.request(this, api.tenant_info, [this.renterId], null, res => {
      if (res) {
        // 获取到租客信息
        this.renter = res
      }
    })
  },
  computed: {
    overdraft () {
      // 计算房间是否是后付费
      return this.roomInfo.pay_type === 2
    },
    leftElectric () {
      if (!this.roomInfo.electric_read) {
        return 0
      }
      return util.getLeftElectric(this.roomInfo)
    },

    /**
        * 是否是指纹锁
        */
    isFingerLock () {
      if (this.roomInfo && this.roomInfo.devices && this.roomInfo.devices.some((device) => (device.device_ability.includes('LOCK') && device.model && device.model === 'lk-19'))) {
        return true
      } else {
        return false
      }
    },

    hasLock () {
      let selfHas // 本房间是否有设备
      let parentHas // 公区房间是否有设备
      if (this.roomInfo.devices) {
        selfHas = this.roomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.LOCK
        })
      }

      if (this.parentRoomInfo.devices) {
        parentHas = this.parentRoomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.LOCK
        })
      }
      return selfHas || parentHas // 房间或者公区有门锁，就显示门锁密码相关
    },
    hasElemeter () {
      let selfHas // 本房间是否有设备
      if (this.roomInfo.devices) {
        selfHas = this.roomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.ELEMETER
        })
      }

      return selfHas // 房间有电表才显示电表相关
    },
    hasAccessControl () {
      return false
    }
  },
  methods: {
    resetForm (name) {
      this.$refs[name].resetFields()
    },
    checkIn () {
      // 租客续租
      if (!this.checkInDate) {
        this.$Message.error('请选择租约有效期!')
        return
      }

      const lease_start = new Date(this.lease.lease_range[0]).getTime()
      const lease_end = new Date(this.checkInDate).getTime()

      const permission_begin = lease_start
      const permission_end = new Date(this.passwordDate).getTime()

      if (lease_end - lease_start < 4 * 60 * 60 * 1000) {
        this.$Message.error('租期至少4小时!')
        return
      }

      if (lease_end < permission_end) {
        this.$Message.error('密码有效期不能大于租约有效期!')
        return
      }

      if (permission_end <= permission_begin) {
        this.$Message.error('密码有效期错误!')
        return
      }

      const params = { lease_end }
      this.operateResult.push({
        params: [api.tenant_leases_update, [this.lease.id], params],
        title: '修改租约有效期'
      })

      this.hasFaceDeviceAndPermission && this.operateResult.push({
        params: [api.face_access_auth_update, [this.lease.id], {auth_start_time: lease_start, auth_end_time: lease_end}],
        title: '修改门禁授权时间'
      })

      // this.changePassword();
      if (this.isFingerLock) { // 如果是指纹锁
        http.request(this, api.leases_grant_record, [this.lease.id], null, (res, error) => {
          if (error || !res) {
            return
          }

          let pos = false
          res.forEach((room) => {
            if (room.passwords && room.passwords.some((password) => (password.type === 2))) {
              pos = true
            }
          })

          if (pos) { // 如果存在指纹密码调用删除
            this.fingerPasswordPeriod()
          }
        })
      }

      this.isResultModalVisible = true
      this.isModalVisible = false
    },

    /**
         * @param {Number} lease_end 租约有效期
         * 修改指纹密码有效期
         */
    fingerPasswordPeriod () {
      const params = {
        permission_begin: new Date(this.lease.lease_range[0]).getTime(),
        permission_end: new Date(this.passwordDate).getTime(),
        permission_status: 2
      }

      const obj = {
        params: [api.finger_password_update_mutil, [this.lease.id], params],
        specialTitle: '修改指纹有效期'
      }

      this.operateResultMulti = obj
    },

    changePassword () {
      let params = {
        permission_begin: new Date(this.lease.lease_range[0]).getTime(),
        permission_end: new Date(this.passwordDate).getTime(),
        permission_status: 2
      }
      this.operateResult.push({
        params: [api.lease_password_edit, [this.lease.id], params],
        title: '修改密码有效期'
      })
    },
    cancelContinue () {
      this.$emit('cancelContinue')
    },
    closeContinueModal () {
      this.$emit('continueSuccess')
    },

    getRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.roomInfo = res
          this.getParentRoomInfo(this.roomInfo.parent_id)
        }
      })
    },
    getParentRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.parentRoomInfo = res
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
    .info-title {
        text-align:right;
        width:120px;
        padding-right:22px;
    }
</style>
